package core.proto;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JSlider;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.border.Border;
import javax.swing.border.LineBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.Highlighter;
import javax.swing.text.JTextComponent;

import org.apache.commons.lang.StringUtils;

import prefuse.util.ui.UILib;
import app.constants.CollabVizConstants;
import app.exceptions.CollabVizException;
import app.service.xml.XMLService;
import app.util.AppUtil;
import app.util.PropertyLoaderUtil;
import app.xml.model.AnnotationTag;
import app.xml.model.DateTag;
import app.xml.model.FileHistoryTag;
import app.xml.model.FileTag;
import app.xml.model.NoteTag;
import core.proto.vis.VizDemoRadial;
import core.util.logging.SimpleLogger;
import core.util.logging.constants.Location;

public class AllComponents extends JPanel implements MouseListener {

	private static final SimpleLogger LOGGER = SimpleLogger.getLogger();

	private static final long serialVersionUID = 1L;

	private static PaintDoc document;

	private static ClosableTabbedPane multipleDocs = new ClosableTabbedPane();

	public static ArrayList<String> openTabs = new ArrayList<String>();

	// private static GroupLayout layout;
	//
	// private static GroupLayout.SequentialGroup hGroup;
	//
	// private static GroupLayout.SequentialGroup vGroup;

	private static JSlider slider;

	static final int width = 1280;

	static final int height = 960;

	private static PropertyLoaderUtil propLoader;

	public static PropertyLoaderUtil getPropLoader() {
		return propLoader;
	}

	private static XMLService xmlService;

	static String imagePath;

	private static String notesImagePath;

	private static String htmlFolderPath = null;

	public static String getHtmlRootFolderPath() {
		return htmlFolderPath;
	}

	static JPanel directory;


	// private static JEditorPane document = new JEditorPane();

	private static JPanel viz = VizDemoRadial.demo(VizDemoRadial.DATA_FILE,
			"name", 360, 440);

	private static JTabbedPane notes = new JTabbedPane();

	private static JSplitPane sp1 = new JSplitPane(JSplitPane.VERTICAL_SPLIT);

	public static JSplitPane sp2 = new JSplitPane();

	private static JSplitPane sp3 = new JSplitPane(JSplitPane.VERTICAL_SPLIT);

	private static JSplitPane sp4 = new JSplitPane();

	private static String htmlFilePath;

	private static FileTag fileTag;

	public static FileTag getFileTag() {
		return fileTag;
	}

	private static JEditorPane historyText;

	private static JScrollPane historyScroll;

	private static JScrollPane notesScroll;

	private static List<String> xmlFileList;

	private static FileTag historyFileTag;

	private static FileHistoryTag hisFileTag;

	private static FileHistoryTag tempHisTag;

	private static String historyFilePath;

	private static String xmlFileName;

	private static JPanel docMiscArea = new JPanel();

	private static JSplitPane sp5 = new JSplitPane(JSplitPane.VERTICAL_SPLIT);

	private static JSplitPane sp6 = new JSplitPane(JSplitPane.VERTICAL_SPLIT);

	private static JPanel notesPanel = new JPanel();

	private static JTextArea notesArea = new JTextArea();

	private static JButton notesSaveButton = new JButton();

	private static String saveOption;

	private static HistoryRenderer historyRenderer;

	static MotionCanvas canvas;


	private static SearchBar searchBar;

	static MouseListener tabDrag;

	public static final int ALL_VIEW = 0;
	public static final int NO_VIZ_VIEW = 1;
	public static final int NO_NOTES_VIEW = 2;
	public static final int NO_VIZNOTES_VIEW = 3;
	private static int selectedView;

	// static float x=0;
	// static float y=0;

	// public static void main(String[] args) throws IOException,
	// CollabVizException {
	// UILib.setPlatformLookAndFeel();
	// if (args.length != 1) {
	// System.out
	// .println("Please pass the absolute path to the config file.");
	// } else {
	// init(args[0]);
	// directory = new FileTree(new File(propLoader
	// .getProp(CollabVizConstants.HTML_FILES_FOLDER)));
	// new AllComponents();
	// }
	//
	// }

	public AllComponents(String path, int selectedView,
			boolean screenCap) throws IOException, CollabVizException {
		super();
		SimpleLogger.setScreenCap(screenCap);
		this.selectedView = selectedView;
		UILib.setPlatformLookAndFeel();
		init(path);
		htmlFolderPath = propLoader
				.getProp(CollabVizConstants.HTML_FILES_FOLDER);
		directory = new FileTree(new File(htmlFolderPath), 1);

		// imagePath = this.getClass()
		// .getResource( CollabVizConstants.COMMENTS_IMG ).toString();
		// notesImagePath = this.getClass()
		// .getResource( CollabVizConstants.NOTES_IMG ).toString();

		imagePath = this.getClass()
				.getResource(CollabVizConstants.COMMENTS_IMG).getPath();
		notesImagePath = this.getClass().getResource(
				CollabVizConstants.NOTES_IMG).getPath();

		document = new PaintDoc();
		document.addMouseListener(this);

		viz.addComponentListener(new ComponentListener() {
			@Override
			public void componentShown(ComponentEvent e_) {
			}

			@Override
			public void componentResized(ComponentEvent e) {
				System.out.println(e.getComponent().getClass().getName()
						+ " --- Resized width = " + viz.getWidth()
						+ " height = " + viz.getHeight());
				for (int i = 0; i < viz.getComponentCount(); i++) {
					if (viz.getComponent(i) instanceof VizDemoRadial) {
						VizDemoRadial visual = (VizDemoRadial) viz
								.getComponent(i);
						visual.resizeAndRun(viz.getWidth(), viz.getHeight());
						sp2.updateUI();
						break;
					}
				}
				LOGGER.log(Location.VZ, "visualization frame resized");
			}

			@Override
			public void componentMoved(ComponentEvent e_) {
			}

			@Override
			public void componentHidden(ComponentEvent e_) {
			}
		});

		setSize(width, height);
		setProperties(directory, 220, 560);
		setProperties(viz, 360, 440);
		viz.setBackground(Color.white);
		setProperties(notes, 360, 260);

		notes = addHistoryComponent(notes);
		notes.setSize(360, 220);
		notes.setVisible(true);
		// notesScroll = new JScrollPane(notes);
		// notesScroll.setSize(360, 220);
		// notesScroll.setVisible(true);

		document.setSize(700, 560);
		JScrollPane scroll = new JScrollPane(document);
		scroll.setSize(700, 560);
		document.setDragEnabled(true);
		document.setEditable(false);

		// create Panel for drop targets to save
		createFileSavePanel();


		JScrollPane docMiscScroll = new JScrollPane(docMiscArea);
		docMiscScroll.setVisible(true);

		// SearchBar
		searchBar = new SearchBar(this);
		notesPanel.add(searchBar);
		save.add(savePanel);
		save.setSize(width, 280);

		    // multiple window view

			multipleDocs.setBackground(Color.GRAY);
			multipleDocs.setSize(700, 560);
			ChangeListener changeListener = new ChangeListener() {
				public void stateChanged(ChangeEvent changeEvent) {
					ClosableTabbedPane tabbedPane = (ClosableTabbedPane) changeEvent
							.getSource();
					int index = tabbedPane.getSelectedIndex();
					if (index != -1 && openTabs.size() > 0) {
						String absPath = openTabs.get(index);
						saveCurrentPath(absPath);
						getFileTree().expandTreeByPath(absPath, false);
						System.out.println("Tab changed to: ");
					}
				}
			};
			multipleDocs.addChangeListener(changeListener);

			// OverlayLayout overlay = new OverlayLayout(multipleDocs);
			// multipleDocs.setLayout( overlay );
			if (selectedView == ALL_VIEW) {
				splitScreen(sp1, viz, notes, 0, .61);
				splitScreen(sp2, multipleDocs, sp1, 1, .55);
			} else if (selectedView == NO_VIZ_VIEW) {
				JPanel gray = new JPanel();
				gray.setSize(360, 220);
				splitScreen(sp1, gray, notes, 0, .61);
				splitScreen(sp2, multipleDocs, sp1, 1, .55);
			} else if (selectedView == NO_NOTES_VIEW) {
				JPanel gray = new JPanel();
				splitScreen(sp1, viz, gray, 0, .71);
				splitScreen(sp2, multipleDocs, sp1, 1, .55);
			} else if (selectedView == NO_VIZNOTES_VIEW) {
				JPanel gray = new JPanel();
				gray.setSize(360, 660);
				splitScreen(sp2, multipleDocs, gray, 1, .60);
			}
			splitScreen(sp4, directory, sp2, 1, 0.17);
			splitScreen(sp3, sp4, save, 0, 0.65);
			add(sp3);

			tabDrag = new MouseListener() {

				@Override
				public void mouseClicked(MouseEvent e) {
					// TODO Auto-generated method stub

				}

				@Override
				public void mouseEntered(MouseEvent e) {
					// TODO Auto-generated method stub

				}

				@Override
				public void mouseExited(MouseEvent e) {
					// TODO Auto-generated method stub

				}

				@Override
				public void mousePressed(MouseEvent e) {
					// TODO Auto-generated method stub

				}

				@Override
				public void mouseReleased(MouseEvent e) {
					// TODO Auto-generated method stub

				}

			};

		
		// createProgressBar("save to database...");
		setVisible(true);
		// setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}

	public void setProperties(JComponent p, int w, int h) {
		Dimension d = new Dimension(w, h);
		p.setPreferredSize(d);
		p.setSize(d);
		p.setVisible(true);
	}

	public static void setFileTag(FileTag fileTag) {
		AllComponents.fileTag = fileTag;
	}

	public static void setHistoryTag(FileHistoryTag historyTag) {
		AllComponents.hisFileTag = historyTag;
	}

	public void splitScreen(JSplitPane sp, Component a, Component b, int x,
			double perc) {
		if (x == 0) {
			sp.setTopComponent(a);
			sp.setBottomComponent(b);
			sp.setSize(a.getWidth(), a.getHeight() + b.getHeight());
			sp.setPreferredSize(getSize());
		} else {
			sp.setLeftComponent(a);
			sp.setRightComponent(b);
			sp.setSize(a.getWidth() + b.getWidth(), a.getHeight());
			sp.setPreferredSize(getSize());
		}
		sp.setDividerLocation(perc);
		// sp.resetToPreferredSizes();
		sp.setVisible(true);
	}

	// public static JScrollPane createDocumentPanel() {
	// PaintDoc doc = new PaintDoc();
	// doc.setDragEnabled( true );
	// doc.setEditable( false );
	// doc.setSize(300, 300);
	// doc.setTransferHandler(new FileTransferHandler());
	// JScrollPane scroll = new JScrollPane(doc);
	// scroll.setSize(300, 300);
	// return scroll;
	// }

	private JTabbedPane addHistoryComponent(JTabbedPane notesPanel) {
		historyText = new JEditorPane();
		// historyText = new JLabel();
		historyText.setDragEnabled(true);
		historyText.setEditable(false);
		historyScroll = new JScrollPane();
		historyScroll.setAutoscrolls(true);
		historyRenderer = new HistoryRenderer();
		historyRenderer.setPropLoader(propLoader);
		historyRenderer.setXMLService(xmlService);
		searchBar = new SearchBar(this);
		historyRenderer = historyRenderer.addHistoryComponent(historyScroll,
				searchBar);
		notesPanel.addTab("History", historyScroll);
		return notesPanel;
	}

	private static JPanel savePanel = null;

	private void createFileSavePanel() {
		// create drop panel - the save panel
		savePanel = new JPanel();
		setProperties(savePanel, 1280, 280);

		canvas = new MotionCanvas(Color.white);
		canvas.setPreferredSize(new Dimension(1280, 280));
		canvas.setBorder(LineBorder.createGrayLineBorder());
		canvas.setTransferHandler(new FileTransferHandler());
		savePanel.add(canvas);
	}

	private static void init(String configFileName) throws CollabVizException {
		propLoader = new PropertyLoaderUtil(configFileName);
		xmlService = new XMLService(propLoader
				.getProp(CollabVizConstants.XML_MAPPING_FILE));
	}

	public static void fileTreeUpdateDoc(CaseNode node, boolean toolbarN,
			int window) throws IOException, CollabVizException {

		// centre the visualizatoin tree to the node
		fileTreeUpdateDoc(node, toolbarN, window, true);
	}

	public static void fileTreeUpdateDoc(CaseNode node, boolean toolbarN,
			int window, boolean rotateNodes) throws IOException,
			CollabVizException {

		// centre the visualizatoin tree to the node
		if (rotateNodes) {
			rotateVisualizationTree(node.toString());
		}
		updateDoc(node.getAbsolutePath());
	}

	public static void visualizationUpdateDoc(final String path)
			throws IOException, CollabVizException {
		// XXX: FOR NOW!!
		// toolbar = true
		// windows = 1
		updateDoc(htmlFolderPath + path);
	}

	private static void rotateVisualizationTree(String nodeName) {
		/**
		 * viz = null; // do not change this line: it helps the GC to collect
		 * the // old viz object faster // create new object viz =
		 * VizDemoRadial.demo( VizDemoRadial.DATA_FILE, "name", 360, 440 );
		 */

		// set focus on w/e file selected
		for (int i = 0; i < viz.getComponentCount(); i++) {
			if (viz.getComponent(i) instanceof VizDemoRadial) {
				VizDemoRadial visual = (VizDemoRadial) viz.getComponent(i);
				visual.externalSetFocus(nodeName);
				sp2.updateUI();
				break;
			}
		}
		// repaint
		viz.invalidate();
		viz.repaint();
	}

	public static void updateDoc(final String absolutePath) throws IOException, CollabVizException {

		File f = new File(absolutePath);
		htmlFilePath = absolutePath;
		xmlFileName = generateXmlFileNameWithTS(f.getAbsoluteFile().getName());
		// tabbed view
			System.out.println(" --------------- window 2 ------------------");
			PaintDoc doc = new PaintDoc();
			doc.addMouseListener(tabDrag);
			doc.setDragEnabled(true);
			doc.setEditable(false);
			doc.setSize(500, 500);
			// doc.setTransferHandler(new FileTransferHandler());
			JScrollPane scroll = new JScrollPane(doc);
			scroll.setSize(300, 300);
			if (openTabs.contains(absolutePath)) {
				multipleDocs.setSelectedIndex(openTabs.indexOf(absolutePath));
			} else {
				String name = absolutePath.substring(absolutePath
						.lastIndexOf('/') + 1, absolutePath.length() - 4);
				if (name.length() > 13) {
					name = name.substring(0, 5) + "..."
							+ name.substring(name.length() - 5, name.length());
				}
				// multipleDocs.addTab(name, scroll);
				JSplitPane jsp = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
				DocumentSearchBar search = new DocumentSearchBar(doc);
				search.setSize(700, 60);
				jsp.setTopComponent(search);
				jsp.setBottomComponent(scroll);
				jsp.setSize(700, 700 + scroll.getHeight());
				jsp.setDividerLocation(0.04);
				jsp.setVisible(true);
				jsp.setEnabled(false);
				multipleDocs.addTab(name, jsp);
				openTabs.add(absolutePath);
				multipleDocs.setSelectedIndex(openTabs.indexOf(absolutePath));
			}
			doc.setPage(f.toURI().toURL());
			doc.validate();
			sp3.validate();
		

		Set<String> highlightTxtSet = loadFileTag(
				f.getAbsoluteFile().getName());
		// loadHistory();
		loadHistoryTable(fileTag, highlightTxtSet);
	}


	static GridLayout grid = new GridLayout(2, 1, 0, 0);

	private static JPanel save = new JPanel( /* grid */);

	private static JPanel saveBarPanel = new JPanel();

	private static JEditorPane saveTextPanel = new JEditorPane();

	JScrollPane saveScrollPanel = new JScrollPane(saveTextPanel);

	private static JProgressBar progressBar = null;

	public static void createProgressBar(String title) {
		progressBar = new JProgressBar(0, 10);
		progressBar.setStringPainted(true);
		Border border = BorderFactory.createTitledBorder(title);
		progressBar.setBorder(border);
		saveBarPanel.add(progressBar, BorderLayout.NORTH);
		progressBar.setVisible(false);
	}

	public static JProgressBar getProgressBar() {
		return progressBar;
	}

	public static JPanel getSaveBarPanel() {
		return saveBarPanel;
	}

	public static JEditorPane getSaveTextPanel() {
		return saveTextPanel;
	}

	private static Set<String> loadFileTag(String fileName)
			throws CollabVizException {
		System.out.println("Loading the file tag.....");
		StringBuffer hisTextArea = new StringBuffer("");

		// int minLimit = 0;
		// int maxLimit = 0;
		// int spaceLimit = 0;
		StringBuffer hisText = new StringBuffer("");
		// Hashtable<Integer, JLabel> sliderTable = new Hashtable<Integer,
		// JLabel>();
		HashSet<String> highlightStr = new HashSet<String>();
		// default implementation for the file tag
		fileTag = new FileTag();

		xmlFileList = listXmlFilesForHtml(htmlFilePath);
			removeHighlights(document);


		// removeHisHighlights(historyText);

		// if (slider != null) {
		// docMiscArea.remove(slider);
		// }
		// if (notesPanel != null) {
		// docMiscArea.remove(notesPanel);
		// }

		if (xmlFileList != null && !xmlFileList.isEmpty()) {
			// minLimit = 0;
			// maxLimit = xmlFileList.size() - 1;
			// if (maxLimit > 0) {
			// spaceLimit = 1;
			// }

			// load the most recent file which has all the history data
			int xmlFileListSize = xmlFileList.size();

			String htmlFileName[] = new File(htmlFilePath).getName().split(
					CollabVizConstants.DOT_REGEX);
			StringBuffer xmlDir = new StringBuffer(PropertyLoaderUtil
					.getProp(CollabVizConstants.XML_FILES_FOLDER_PATH));
			xmlDir.append(CollabVizConstants.FILE_DELIMITER);
			xmlDir.append(htmlFileName[0]);
			xmlDir.append(CollabVizConstants.FILE_DELIMITER);
			String fileDir = xmlDir.toString();
			xmlDir.append(xmlFileList.get(xmlFileListSize - 1));

			// sliderTable = AppUtil.getCalLabelTable(xmlFileList, fileDir,
			// xmlService);

			historyFileTag = (FileTag) xmlService.unmarshall(xmlDir.toString());
			fileTag = (FileTag) xmlService.unmarshall(xmlDir.toString());

			// loading history
			tempHisTag = null;
			// loadHistory();

			if (historyFileTag != null) {
				List<NoteTag> notes = historyFileTag.getNote();
				List<AnnotationTag> annotations = historyFileTag
						.getAnnotation();
				if (notes != null && !notes.isEmpty()) {
					// hisText.append("<html><body>");
					// hisText.append("Notes: <br>");
					for (NoteTag note : notes) {
						// hisText.append("<font color='blue'>");
						// hisText.append(note.getTimeStamp());
						// hisText.append(":");
						// hisText.append(note.getContent());
						// hisText.append("</font>");
						// hisText.append("<br>");
						highlightStr.add(note.getContent());
					}
				}
				if (annotations != null && !annotations.isEmpty()) {
					// if (notes == null || notes.isEmpty()) {
					// hisText.append("<html><body>");
					// }
					// hisText.append("Annotations:<br>");
					for (AnnotationTag annot : annotations) {
						// hisText.append("<font color='red'>");
						// hisText.append(annot.getTimeStamp());
						// hisText.append(" : ");
						// hisText.append("<i>");
						// hisText.append(annot.getKey());
						// hisText.append("</i>");
						// hisText.append(" : ");
						// hisText.append(annot.getValue());
						// hisText.append("</font>");
						// hisText.append("<br>");
						// Point commentIconPt = highlight(multipleDocs, annot
						// .getKey(), Color.yellow);
						// if (commentIconPt != null) {
						// document.set((int) commentIconPt.getX(),
						// (int) commentIconPt.getY(), annot.getKey());
						// document.paintComponents(document.getGraphics());
						// }
						highlightStr.add(annot.getKey());
						highlightStr.add(annot.getValue());
					}
					// if (hisText.length() > 0) {
					// hisText.append("</body></html>");
					// }
				}
			}
		}
		if (fileTag != null) {
			List<NoteTag> notes = fileTag.getNote();
			StringBuffer notesStr = new StringBuffer("");
			if (notes != null && !notes.isEmpty()) {
				hisTextArea.append("NOTES:\n");
				for (NoteTag note : notes) {
					notesStr.append(note.getContent() + "\n");
				}
			}
			// loadNotes(notesStr.toString());
		} else {
			fileTag = new FileTag();
		}

		// displaying the history bar towards bottom of the doc panel
		if (historyText == null) {
			// historyText = new JLabel(hisText.toString());
		} else {
			// historyText.setText(hisText.toString());
		}
		// slider = new JSlider(minLimit, maxLimit, spaceLimit);
		// SliderChangeListener listener = new SliderChangeListener();
		// slider.addChangeListener(listener);
		// slider.setLabelTable(sliderTable);
		// slider.setMajorTickSpacing(10);
		// slider.setMinorTickSpacing(1);
		// slider.setPaintTicks(true);

		// if (maxLimit > 0) {
		// slider.setPaintLabels(true);
		// }
		// slider.setVisible(true);
		// slider.setEnabled(true);
		// slider.setBounds(0, 0, 500, 50);
		// slider.setName("");

		// docMiscArea.add(slider);
		// docMiscArea.add(notesPanel);
		highlightAnnotations(fileTag.getAnnotation());
		return highlightStr;
	}

	public static void highlightAnnotations(List<AnnotationTag> annoList) {
		if (annoList == null || annoList.isEmpty()) {
			// System.out
			// .println("WARN: The incoming annotation list is null or empty.");
			return;
		}
		removeHighlights(document);
		for (AnnotationTag annot : annoList) {
			try {
				highlight(multipleDocs, annot.getKey(), Color.yellow);
				// if (commentIconPt != null) {
				// document.set((int) commentIconPt.getX(),
				// (int) commentIconPt.getY(), annot.getKey());
				// document.paintComponents(document.getGraphics());
				// }
			} catch (Throwable th) {
				System.out
						.println("ERROR: error while highlighting the annotations in document for -- "
								+ annot.getKey() + ":" + annot.getValue());
				th.printStackTrace();
			}
		}

	}

	public static List<String> listXmlFilesForHtml(String htmlFilePath)
			throws CollabVizException {
		if (htmlFilePath == null || StringUtils.isEmpty(htmlFilePath)) {
			return null;
		}
		String htmlFileName[] = new File(htmlFilePath).getName().split(
				CollabVizConstants.DOT_REGEX);
		StringBuffer htmlDir = new StringBuffer(PropertyLoaderUtil
				.getProp(CollabVizConstants.XML_FILES_FOLDER_PATH));
		htmlDir.append(CollabVizConstants.FILE_DELIMITER);
		htmlDir.append(htmlFileName[0]);

		FilenameFilter filter = new FilenameFilter() {
			@Override
			public boolean accept(File dir, String name) {
				String tokens[] = name.split(CollabVizConstants.DOT_REGEX);
				if (tokens == null || tokens.length != 2) {
					return false;
				}
				if ("xml".equals(tokens[1])) {
					return true;
				}
				return false;
			}
		};

		File htmlDirName = new File(htmlDir.toString());
		String tempFileList[] = htmlDirName.list(filter);
		List<String> resultList = new ArrayList<String>();
		if (tempFileList != null && tempFileList.length > 0) {

			resultList = Arrays.asList(tempFileList);
		}

		return resultList;
	}

	private static void loadNotes(String notes) {
		System.out.println("Loading the notes : " + notes);
		if (notes == null || StringUtils.isEmpty(notes)) {
			notes = "";
		}
		notesArea.setText(notes);
	}

	private static String generateXmlFileName(String fileName)
			throws CollabVizException {
		StringBuffer result;
		if (fileName == null || StringUtils.isEmpty(fileName)) {
			throw new CollabVizException(
					CollabVizConstants.INCOMING_PARAM_EMPTY_ERROR);
		}
		result = new StringBuffer();
		String fileNametemp[] = fileName.split(CollabVizConstants.DOT_REGEX);
		if (fileNametemp != null && fileNametemp.length > 0) {
			result.append(propLoader
					.getProp(CollabVizConstants.XML_FILES_FOLDER_PATH));
			result.append(CollabVizConstants.FILE_DELIMITER);
			result.append(fileNametemp[0]);
			result.append(CollabVizConstants.DOT_CHAR);
			result.append(CollabVizConstants.XML);
			// }
		}
		return result.toString();
	}

	private static String generateXmlFileNameWithTS(String fileName)
			throws CollabVizException {
		StringBuffer result;
		if (fileName == null || StringUtils.isEmpty(fileName)) {
			throw new CollabVizException(
					CollabVizConstants.INCOMING_PARAM_EMPTY_ERROR);
		}
		result = new StringBuffer();
		long timestamp = System.currentTimeMillis();
		String fileNametemp[] = fileName.split(CollabVizConstants.DOT_REGEX);
		if (fileNametemp != null && fileNametemp.length > 0) {
			result.append(propLoader
					.getProp(CollabVizConstants.XML_FILES_FOLDER_PATH));
			result.append(CollabVizConstants.FILE_DELIMITER);
			result.append(fileNametemp[0]);
			AppUtil.createDir(result.toString());
			result.append(CollabVizConstants.FILE_DELIMITER);
			result.append(fileNametemp[0]);
			result.append("_");
			result.append(timestamp);
			result.append(CollabVizConstants.DOT_CHAR);
			result.append(CollabVizConstants.XML);
			// }
		}
		return result.toString();
	}

	private static void updateNotes(String notes, String xmlFileName)
			throws CollabVizException {
		if (notes == null || StringUtils.isEmpty(notes)) {
			throw new CollabVizException(
					CollabVizConstants.INCOMING_PARAM_EMPTY_ERROR);
		}
		// FileTag fileTag = null;
		if (fileTag == null) {
			fileTag = new FileTag();
			fileTag.setFilePath(htmlFilePath);
			fileTag.setName(xmlFileName);
		}
		List<NoteTag> notesTagList = fileTag.getNote();
		if (notesTagList == null || notesTagList.isEmpty()) {
			notesTagList = new ArrayList<NoteTag>();
		}
		NoteTag noteTag = new NoteTag();
		noteTag.setContent(notes);
		noteTag.setTimeStamp((new Date()).toString());
		notesTagList.add(noteTag);

		// update the history component
		fileTag.setNote(notesTagList);
		if (hisFileTag == null) {
			hisFileTag = new FileHistoryTag();
			hisFileTag.setDateTagList(new ArrayList<DateTag>());
		}
		ArrayList<DateTag> dtList = new ArrayList<DateTag>();
		DateTag dtTag = new DateTag();
		List<NoteTag> noteList = new ArrayList<NoteTag>();
		NoteTag note = new NoteTag();
		note.setContent(notes);
		noteList.add(note);
		dtTag.setTimeStamp(getDateString(xmlFileName
				.split(CollabVizConstants.DOT_REGEX)[0].split("_")[1]));
		dtTag.setFileName(new File(htmlFilePath).getName());
		dtTag.setFilePath(xmlFileName);
		dtTag.setNote(noteList);
		dtList.add(dtTag);

		hisFileTag.getDateTagList().addAll(dtList);
	}

	private void updateAnnotation(int xVal, int yVal, String key, String value,
			String xmlFileName) throws CollabVizException {
		System.out.println("updateAnnotation(): starts");

		if (key == null || StringUtils.isEmpty(key) || xmlFileName == null
				|| StringUtils.isEmpty(xmlFileName)) {
			throw new CollabVizException(
					CollabVizConstants.INCOMING_PARAM_EMPTY_ERROR);
		}
		// FileTag fileTag = null;
		if (fileTag == null) {
			fileTag = new FileTag();
			fileTag.setFilePath(htmlFilePath);
			fileTag.setName(xmlFileName);
		}

		List<AnnotationTag> annoTagList = fileTag.getAnnotation();
		if (annoTagList == null || annoTagList.isEmpty()) {
			annoTagList = new ArrayList<AnnotationTag>();
		}

		// update the existing stuff
		List<AnnotationTag> modifiedList = new ArrayList<AnnotationTag>();
		boolean modified = false;
		for (AnnotationTag annotTag : annoTagList) {
			if (annotTag.getKey().equals(key)) {
				annotTag.setValue(value);
				modified = true;
			}
			modifiedList.add(annotTag);
		}
		if (modified) {
			fileTag.setAnnotation(modifiedList);
		} else {

			AnnotationTag annoTag = new AnnotationTag();
			annoTag.setKey(key);
			annoTag.setValue(value);
			annoTag.setTimeStamp((new Date()).toString());
			annoTag.setX(xVal);
			annoTag.setY(yVal);
			annoTagList.add(annoTag);
			fileTag.setAnnotation(annoTagList);
		}

		// update the history component
		if (hisFileTag == null) {
			hisFileTag = new FileHistoryTag();
			hisFileTag.setDateTagList(new ArrayList<DateTag>());
		}
		ArrayList<DateTag> dtList = new ArrayList<DateTag>();
		DateTag dtTag = new DateTag();
		List<AnnotationTag> annotList = new ArrayList<AnnotationTag>();
		AnnotationTag annot = new AnnotationTag();
		annot.setKey(key);
		annot.setValue(value);
		annotList.add(annot);
		dtTag.setFileName(new File(htmlFilePath).getName());
		dtTag.setFilePath(xmlFileName);
		dtTag.setTimeStamp(getDateString(xmlFileName
				.split(CollabVizConstants.DOT_REGEX)[0].split("_")[1]));
		dtTag.setAnnotation(annotList);
		dtList.add(dtTag);
		hisFileTag.getDateTagList().addAll(dtList);
		System.out.println("updateAnnotation(): ends");
	}

	private void removeAnnotation(String key) {
		if (key == null || StringUtils.isEmpty(key)) {
			return;
		}
		List<AnnotationTag> modifiedList = new ArrayList<AnnotationTag>();
		List<AnnotationTag> annotList = fileTag.getAnnotation();
		if (annotList != null && !annotList.isEmpty()) {
			for (AnnotationTag annot : annotList) {
				if (key.equals(annot.getKey())) {
					continue;
				}
				modifiedList.add(annot);
			}
		}
		fileTag.setAnnotation(modifiedList);
	}


	private static Point highlight(ClosableTabbedPane tabbedPane,
			String pattern, Color color) throws CollabVizException {
		JSplitPane splitPane = (JSplitPane) tabbedPane.getSelectedComponent();
		// if (splitPane.getLeftComponent() instanceof JTextComponent) {
		// System.out.println("-----------");
		// } else if (splitPane.getRightComponent() instanceof JTextComponent) {
		// System.out.println("------ right -----");
		// }
		JScrollPane textScroll = (JScrollPane) splitPane.getRightComponent();
		JTextComponent textComp = (JTextComponent) textScroll.getViewport()
				.getView();

		Highlighter.HighlightPainter myHighlightPainter = new TextHighlighter(
				color);
		// List<Point> result = new ArrayList<Point>();
		Point result = new Point();

		// highlight the text that is displayed on screen currently
		pattern = pattern.toLowerCase();
		try {

			Highlighter hilite = textComp.getHighlighter();
			Document doc = textComp.getDocument();
			String text = doc.getText(0, doc.getLength());
			text = text.toLowerCase();
			int pos = 0;
			int temPos = -1;
			// Search for pattern
			while ((pos = text.indexOf(pattern, pos)) >= 0) {
				// Create highlighter using private painter and apply around
				// pattern

				hilite.addHighlight(pos, pos + pattern.length(),
						myHighlightPainter);
				temPos = pos;
				pos += pattern.length();
			}
			// Rectangle rect = document.modelToView(temPos);
			// result.x = (int) rect.getMaxX();
			// result.y = (int) rect.getMinY() - 30;

		} catch (BadLocationException e) {
			System.out.println("WARN: error while highlighting...");
			throw new CollabVizException(e);
		}
		return result;
	}

	// COMENTING AS THE CODE IS NOT USED
	// private static class SliderChangeListener implements ChangeListener {

	// public void stateChanged(ChangeEvent e) {
	// JSlider source = (JSlider) e.getSource();
	// if (!source.getValueIsAdjusting()) {
	// int fps = (int) source.getValue();
	// try {
	// loadFiles(fps);
	// } catch (CollabVizException exp) {
	// exp.printStackTrace();
	// }
	// }
	// }
	// }
	// private static void loadFiles(int fileNumber) throws CollabVizException {
	// if (fileNumber < 0) {
	// return;
	// }
	// removeHighlights(document);
	// int fileIndex = 0;
	// if (fileNumber > 0) {
	// fileIndex = fileNumber - 1;
	// }
	// System.out.println("File index: " + fileIndex + " fileNumber: "
	// + fileNumber);
	// String xmlFileName = xmlFileList.get((fileNumber)).split(
	// CollabVizConstants.DOT_REGEX)[0];
	// System.out.println("File selected : " + xmlFileName);
	// StringBuffer tempHtmlPath = new StringBuffer("");
	// tempHtmlPath.append(PropertyLoaderUtil
	// .getProp(CollabVizConstants.XML_FILES_FOLDER_PATH));
	// tempHtmlPath.append(CollabVizConstants.FILE_DELIMITER);
	// tempHtmlPath.append(new File(htmlFilePath).getAbsoluteFile().getName()
	// .split(CollabVizConstants.DOT_REGEX)[0]);
	// tempHtmlPath.append(CollabVizConstants.FILE_DELIMITER);
	// tempHtmlPath.append(xmlFileName);
	// tempHtmlPath.append(CollabVizConstants.DOT_CHAR);
	// tempHtmlPath.append("xml");
	// System.out.println("INFO: File loaded: " + tempHtmlPath.toString());
	// load the file xml
	// fileTag = (FileTag) xmlService.unmarshall(tempHtmlPath.toString());
	// List<AnnotationTag> annoTagList = fileTag.getAnnotation();
	// if (annoTagList != null && !annoTagList.isEmpty()) {
	// StringBuffer annoText = new StringBuffer("");
	// int xVal = 0;
	// int yVal = 0;
	// for (AnnotationTag anno : annoTagList) {
	// annoText.append(anno.getKey());
	// xVal = anno.getX();
	// yVal = anno.getY();
	// highlight(document, anno.getKey(), Color.YELLOW);
	// document.set(xVal, yVal, anno.getKey());
	// document.paintComponents(document.getGraphics());
	// }
	// }
	// StringBuffer notes = new StringBuffer("");
	// List<NoteTag> notesList = fileTag.getNote();
	// if (notesList != null && !notesList.isEmpty()) {
	// for (NoteTag noteTag : notesList) {
	// notes.append(noteTag.getContent());
	// notes.append("\n");
	// }
	// }
	// System.out.println("Notes: " + notes.toString());
	// loadNotes(notes.toString());
	// }
	@Override
	public void mouseClicked(MouseEvent e) {

	}

	@Override
	public void mouseEntered(MouseEvent e) {

	}

	@Override
	public void mouseExited(MouseEvent e) {

	}

	@Override
	public void mousePressed(MouseEvent e) {

	}

	@Override
	public void mouseReleased(MouseEvent e) {
	}

	// COMMENTED AS THIS CODE IS NOT USED ANY MORE
	// private static void removeCommentsComponents(String selectedText,
	// List<AnnotationTag> annotList) {
	// if (annotList == null || annotList.isEmpty()) {
	// Component compList[] = document.getComponents();
	// if (compList != null && compList.length > 0) {
	// for (Component component : compList) {
	// if (component instanceof JLabel) {
	// JLabel label = (JLabel) component;
	// if (selectedText.equals(label.getName())) {
	// label.setEnabled(false);
	// label.setVisible(false);
	// document.remove(label);
	// }
	// }
	// }
	// }
	// } else {
	// for (AnnotationTag annotTag : annotList) {
	// Component compList[] = document.getComponents();
	// if (compList != null && compList.length > 0) {
	// for (Component component : compList) {
	// if (component instanceof JLabel) {
	// JLabel label = (JLabel) component;
	// if (annotTag.getKey().equals(label.getName())) {
	// label.setEnabled(false);
	// label.setVisible(false);
	// document.remove(label);
	// }
	// }
	// }
	// }
	// }
	// }
	// }

	public static void removeHighlights(JTextComponent textComp) {
		Highlighter hilite = textComp.getHighlighter();
		if (hilite == null) {
			return;
		}
		Highlighter.Highlight[] hilites = hilite.getHighlights();

		if (hilites == null || hilites.length == 0) {
			return;
		}
		for (int i = 0; i < hilites.length; i++) {

			hilite.removeHighlight(hilites[i]);
		}
		// added here for temp fix
		Component compoList[] = document.getComponents();
		if (compoList != null && compoList.length > 0) {
			for (Component compo : compoList) {
				if (compo instanceof JLabel) {
					compo.setVisible(false);
					compo.setEnabled(false);
					document.remove(compo);
				}
			}
		}
	}


	private static String getDateString(String timeStamp) {
		if (timeStamp == null || StringUtils.isEmpty(timeStamp)) {
			return (new Date().toString());
		}
		DateFormat formatter = new SimpleDateFormat(
				CollabVizConstants.DATE_FORMAT);
		Calendar cal = Calendar.getInstance();
		cal.setTimeInMillis(Long.parseLong(timeStamp));
		return (formatter.format(cal.getTime()));
	}


	public static void highlightAnnotInHistoryTable(String key, String value) {
		if (key == null || StringUtils.isEmpty(key) || value == null
				|| StringUtils.isEmpty(value)) {
			return;
		}
		HashSet<String> cellValueSet = new HashSet<String>();
		cellValueSet.add(key);
		cellValueSet.add(value);
		Rectangle rect = historyRenderer.highlightTextSet(cellValueSet);
		if (rect != null) {
			historyRenderer.getJeksTable().scrollRectToVisible(rect);
		}
	}

	private static void loadHistoryTable(FileTag fileTag, Set<String> highText)
			throws CollabVizException {
		if (htmlFilePath == null || StringUtils.isEmpty(htmlFilePath)) {
			System.out.println("ERROR: No Html file is loaded...");
			return;
		}
		if (historyFilePath == null || StringUtils.isEmpty(historyFilePath)) {
			StringBuffer historyFile = new StringBuffer(propLoader
					.getProp(CollabVizConstants.XML_FILES_FOLDER_PATH));
			historyFile.append(CollabVizConstants.FILE_DELIMITER);
			historyFile.append(CollabVizConstants.HISTORY_FILE_NAME);
			historyFilePath = historyFile.toString();
		}

		// if (tempHisTag == null) {
		hisFileTag = (FileHistoryTag) xmlService.unmarshall(historyFilePath);
		// } else {
		if (hisFileTag == null) {
			hisFileTag = new FileHistoryTag();
			// hisFileTag.setDateTagList(tempHisTag.getDateTagList());
			System.out.println("WARN: No history to be loaded.");
		}
		// else {
		// List<DateTag> dtTagList = hisFileTag.getDateTagList();
		// dtTagList.addAll(tempHisTag.getDateTagList());
		// hisFileTag.setDateTagList(dtTagList);
		// xmlService.marshall(historyFilePath, hisFileTag);
		// }
		// }

		historyRenderer.setFileTag(fileTag);
		historyRenderer.setXMLFileName(xmlFileName);
		historyRenderer.setHtmlFilePath(htmlFilePath);
		historyRenderer.setHistoryTag(hisFileTag);
		Rectangle rect = historyRenderer.loadDataOri(highText);
		historyRenderer.setViewportViewForHistory(historyScroll);
		JScrollBar scrollBar = historyScroll.getVerticalScrollBar();
		scrollBar.setValue(scrollBar.getMaximum());

		// for the search within history content
		historyRenderer.loadData(highText, null);
		// historyScroll.setViewportView(historyRenderer.getJeksTable());
		// if (rect != null) {
		// historyRenderer.getJeksTable().scrollRectToVisible(rect);
		// historyRenderer.scrollToBotton(rect);

		// }
	}

	public static HistoryRenderer getHistoryRenderer() {
		return historyRenderer;
	}

	public static FileTree getFileTree() {
		return (FileTree) directory;
	}

	public static JEditorPane getDocumentPane() {
		return (JEditorPane) document;
	}

	public static ClosableTabbedPane getMultipleDocs() {
		return multipleDocs;
	}

	private static String previousAbsPath = null;
	private static String currentAbsPath = null;

	public static String getPreviousPath() {
		return previousAbsPath;
	}

	public static void saveCurrentPath(String absPath) {
		previousAbsPath = currentAbsPath;
		currentAbsPath = absPath;
	}

	public static String getCurrentPath() {
		return currentAbsPath;
	}
}
